const fs = require('fs')
const path = require('path')
const chalk = require('chalk')


module.exports = function (name, title) {
  const dirUrl = path.resolve(process.cwd(), `./src/modules/${ name }`)
  try {
    if (!fs.existsSync(dirUrl))
      fs.mkdirSync(dirUrl)
    const resolve = dir => path.join(process.cwd(), `./src/modules/${ name }/${ dir }`)
    // 写入入口文件
    addConfig(name, resolve(`${ name }.js`))
    // 写入入口挂在的vue文件
    addVue(name, resolve(`${ name }.vue`))
    // 写入路由指向的文件
    addComponent(name, path.resolve(process.cwd(), `./src/pages/${ name }/${ name }.vue`), title)
    // 写入路由配置文件
    addRouter(name, resolve('router.js'), title)
    // 写入html文件
    addHtml(name, path.resolve(process.cwd(), `./public/${ name }.html`))
  } catch (err) {
    console.log(chalk.red(err))
  }
}

function addConfig(name, url) {
  const template = `
import Vue from 'vue'
import App from './${name }.vue'
import router from './router'

import axios from 'axios'
Vue.http = Vue.prototype.$http = axios;

Vue.use(require('vue-wechat-title'))

import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI);

new Vue({
    router,
    render: h => h(App)
}).$mount('#${name }')
  `
  try {
    fs.writeFileSync(url, template, 'utf8')
    console.log(chalk.blue('ok >>>'), `${ name }.js文件写入完成`)
  } catch (err) {
    console.log(chalk.red(err))
  }
}


function addVue(name, url) {
  const template = `
    <template>
      <div id="${name }" v-wechat-title="$route.meta.title">
        <router-view></router-view>
      </div>
    </template>

    <script>
      export default {
        name: "${name}"
      }
    </script>
  `
  try {
    fs.writeFileSync(url, template, 'utf8')
    console.log(chalk.blue('ok >>>'), `${ name }.vue文件写入完成`)
  } catch (err) {
    console.log(chalk.red(err))
  }
}

function addRouter(name, url, title) {
  const template = `
  import Vue from 'vue'
  import VueRouter from 'vue-router'

  Vue.use(VueRouter)

  const routes = [
    { path: '/', name: '${name }', component: r => { require(['../../pages/${ name }/${ name }'], r) }, meta: { title: '${ title || name }' }}
  ]

  export default new VueRouter({
    routes: routes
  })
  `
  try {
    fs.writeFileSync(url, template, 'utf8')
    console.log(chalk.blue('ok >>>'), `router.js文件写入完成`)
  } catch (err) {
    console.log(chalk.red(err))
  }
}

function addComponent(name, url, title) {
  const dirUrl = path.resolve(process.cwd(), `./src/pages/${ name }`)
  if (!fs.existsSync(dirUrl)) fs.mkdirSync(dirUrl)
  const template = `
<template>
  <div>
    ${title || name }组件
  </div>
</template>

<script>
  import { login } from "@/api/common";
  export default {
    name: "${name}",
    data() {
      return {
        items: [],
      }
    },
    mounted() {
      this.login()
    },
    methods: {
      // 登录
      login(){
        login('test','111111')
          .then( res=> {
            console.info(res.data);
          })
          .catch(function (error){
            console.log(error);
          });
      },
      // 调用api获得列表
      getLists(){
        let params={
            '[]': {
                'TableName': {'@column': 'id,name'}
            }
        };
        get(params)
          .then( res=> {
            this.items = res.data["[]"];
          })
          .catch(function (error){
              console.log(error);
          });
      },
    }
  }
</script>

<style scoped>

</style>
  `
  try {
    fs.writeFileSync(url, template, 'utf8')
    console.log(chalk.blue('ok >>>'), `pages/${ name }下的${ name }.vue文件写入完成`)
  } catch (err) {
    console.log(chalk.red(err))
  }
}

function addHtml(name, url) {
  const template = `
  <!DOCTYPE html>
  <html lang="en">
  <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width,initial-scale=1.0">
      <title><%= htmlWebpackPlugin.options.title %></title>
  </head>
  <body>
  <div id="${name }"></div>
  </body>
  </html>
  `
  try {
    fs.writeFileSync(url, template, 'utf8')
    console.log(chalk.blue('ok >>>'), `${ name }.html文件写入完成`)
  } catch (err) {
    console.log(chalk.red(err))
  }
}